import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

import store from '../store/index'

const routes = [

  // 登陆
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/menus',//vue3基本语法演示
    name: 'menus',
    redirect:'/profile',
    component: () => import('../views/menus.vue'),
    children: [
      {
        path: '/profile',
        name: 'profile',
        component: () => import('../views/profile.vue'),
      },
      {
        path: '/chart',
        name: 'chart',
        component: () => import('../views/chart.vue'),
      },
      {
        path: '/manage',
        name: 'manage',
        component: () => import('../views/user/manage.vue'),
      },
      {
        path: '/role',
        name: 'role',
        component: () => import('../views/user/role.vue'),
      },
      {
        path: '/permission',
        name: 'permission',
        component: () => import('../views/user/permission.vue'),
      },
      {
        path: '/ranking',
        name: 'ranking',
        component: () => import('../views/article/ranking.vue'),
      },
      {
        path: '/create',
        name: 'create',
        component: () => import('../views/article/create.vue'),
      },
    ]
  },
  //根目录,到登录页面
  {
    path: '/',
    redirect: '/login'
  },
  //找不到页面到404,！！注意vue3里不能用*
  {
    path: '/:catchAll(.*)',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHashHistory(), // hash模式：createWebHashHistory，history模式：createWebHistory
  routes
})

// import { fn } from '../utils/router'

function loadRoute() {
  const token = store.state.userInfo
  let menulist = store.state.menuList
  // console.log(123, token); console.log(321, menulist);
  let arr = []
  // setTimeout(() => {
  //   if (token && menulist) {
  //     menulist.forEach(item => {
  //       arr.push({
  //         path: '/user/' + item,
  //         name: item,
  //         component: () => import(`../views/list/${item}.vue`)
  //       })
  //       // router.addRoute('menus', item)
  //     })
  //   }
  //   console.log(arr);
  // }, 300)

}
loadRoute()

// arr.push({
// path: '/' + item.path,
// name: item.path,
// component: () => import(`../views/list/${item.path}.vue`)
// })


router.beforeEach((to, from, next) => {
  const token = store.state.userInfo
  const islogin = (to.path === "/login")
  if (islogin && token) {
    return next({ name: 'menus' })
  }
  if (!islogin && !token) {
    return next({ name: 'login' })
  }
  next()
})



// router.beforeEach((to, from, next) => {
//   const token = store.state.userInfo
//   // console.log(token)
//   const isLogin = (to.path === '/login')
//   // 如果有token，并且是在登录页，那么跳转到首页
//   if (token && isLogin) {
//     return next({ name: 'homeview' })
//   }
//   // 如果没有token，并不是在登录页，跳转到登录页
//   if (!token && !isLogin) {
//     return next({ name: 'login' })
//   }
//   next()
// })

export default router
